#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <cstring>
#include <memory>
#include <pthread.h>
#include <sys/wait.h>
#include "Logger.hpp"
#include "Common.hpp"
#include "ThreadPool.hpp"
#include <functional>

using namespace LogMudule;
using namespace ThreadPoolMudule;
const u_int16_t defport = 8888;
const int backlog = 8;
const int deffd = -1;

using task_t = std::function<void()>;

class TcpSever
{
private:
    struct ThreadData
    {
        int sockfd;
        TcpSever *self;
    };

    void HanderTask(int sockfd)
    {
        while (true)
        {

            // 读取信息
            char inbuffer[1024];
            memset(inbuffer, 0, sizeof(inbuffer));
            int n = ::read(sockfd, inbuffer, sizeof(inbuffer) - 1);
            if (n > 0)
            {
                LOG(LogLevel::INFO) << "client# " << inbuffer <<"  "<<sockfd;
                // 写入信息
                inbuffer[n] = 0;
                ::write(sockfd, inbuffer, sizeof(inbuffer));
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client close!";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::ERROR) << "read error!";
                close(sockfd);
                break;
            }
        }
    }

public:
    TcpSever(u_int16_t port)
        : _port(port),
          _isrunning(false),
          _listensockfd(deffd)
    {
    }
    static void *hander(void *arg)
    {
        pthread_detach(pthread_self());
        ThreadData *data = (ThreadData *)arg;
        data->self->HanderTask(data->sockfd);
        delete data;
        return nullptr;
    }
    void SeverInit()
    {
        // 创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket 创建失败!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket 创建成功!";

        // 填充本地信息
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);

        // 绑定
        int n = ::bind(_listensockfd, Conv(&local), sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind 失败!";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind 成功!";

        // 监听,获取连接，返回文件描述符
        n = listen(_listensockfd, backlog);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen 失败!";
            exit(3);
        }
        LOG(LogLevel::INFO) << "listen 成功!";
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 接收信息
            int sockfd = accept(_listensockfd, Conv(&peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::ERROR) << "accept error!";
                continue;
            }
            LOG(LogLevel::INFO) << "accept success!";
            // verion 1
            //  HanderTask(sockfd);
            // version 2
            //     pid_t pid = fork();
            //     if (pid < 0)
            //     {
            //         LOG(LogLevel::ERROR) << "fork error!";
            //         close(sockfd);
            //         continue;
            //     }
            //     else if (pid == 0)
            //     {
            //         close(_listensockfd);
            //         if (fork() > 0)
            //         {
            //             exit(0);
            //         }
            //         HanderTask(sockfd);
            //         exit(0);
            //     }
            //     int rid = waitpid(pid, nullptr, 0);
            //     if(rid < 0)
            //     {
            //         LOG(LogLevel::WARNING) << "waitpid error!";
            //     }
            //     close(sockfd);
            //
            // version 3
            // pthread_t tid;
            // ThreadData *data = new ThreadData;
            // data->sockfd = sockfd;
            // data->self = this;
            // int n = pthread_create(&tid, nullptr, hander, data);
            // if (n != 0)
            // {
            //     LOG(LogLevel::ERROR) << "pthread_create error!";
            //     close(sockfd);
            //     continue;
            // }
            // version 4
           // task_t f = std::bind(&TcpSever::HanderTask, this, sockfd); // 构建任务

            ThreadPool<task_t>::getInstance()->Equeue([this, sockfd]() {
                HanderTask(sockfd);
            });
            
        }
    }

private:
    int _listensockfd;
    bool _isrunning;
    u_int16_t _port;
};